package com.changgou.system.service;



import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
import java.util.UUID;

/**
 *    MD5工具类
 *
 */
public class MD5Utils {

    //encryption
    /**
     *  将字符串通过MD5得到计算后的MD5信息
     * @param str  字符串
     * @return
     */
    static String getMD5(String str){
        try {
            //通过getInstance获取到一个MD5加密计算的对象
            MessageDigest md = MessageDigest.getInstance("MD5");
            //计算MD5函数
            md.update(str.getBytes());
            //此处百度的
            //digest()最后确定返回md5 hash值，返回值为字符串。因为md5 hash值是16位的hex值，实际上就是8位的字符
            return new BigInteger(1,md.digest()).toString(32);
            //   105ism5b2p0tdpcio72kmi6irg

        }catch (Exception e){

            return str;
        }

    }

   public static String generatePassword(String password){
        //获取随机生成的字符串
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 18);
        //获取到随机生成的uuid 和 通过MD5编译后的字符串
        password = getMD5(password + uuid);

        //8137D5C35445BB9D73E2EF51C0ADA2F2
       //43pimv3h2e3qvvdlhas67kk8o4   //24
       //  $2a
        // password 【123】= 105ism5b2p0tdpcio72kmi6irg8e74b79f1e2c6b2b 密文
        char[] cs = new char[44];
        for (int i = 0; i < 44; i += 4) {
            cs[i] = password.charAt(i / 4 * 2);
            char c = uuid.charAt(i / 4);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 4 * 2 + 1);
        }

  return password;

    }

    /**
     * 校验密码是否正确
     */
    public static boolean info(String password, String md5) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 1; i < 44; i += 3) {
            cs1[i / 3 * 1] = md5.charAt(i);
            cs1[i / 3 * 2 + 1] = md5.charAt(i + 1);
            cs2[i / 4] = md5.charAt(i + 1);
        }
        String salt = new String(cs2);

        return getMD5(password + salt).equals(new String(cs1));
    }




    /**
     *     获取加密后的密码
     * @param password
     * @return
     */
   /* static String getMD5(String password){
        //获取随机数
        Random random = new Random();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(random.nextInt(123456)).append(random.nextInt(11111));


return null;
    }
*/




}
